import datetime

import sqlalchemy
from flask import Blueprint, request, session, redirect, url_for, jsonify, render_template

from config import md5_encrypt
from models import User, db

bp = Blueprint('register', __name__)
import hashlib




@bp.route('/register', methods=['GET', 'POST'])
def register():
    # 已登录
    if 'username' in session:
        return redirect(url_for('index.index'))

    if request.method == 'POST':
        data = request.json
        username = data.get('username')
        password = md5_encrypt(data.get('password'))
        email = data.get('email')

        if len(username)<3 or len(password)<3 or len(email)<3 :
            return jsonify({'error': '表单不完整'})

        existing_user = User.query.filter_by(username=username).first()
        if existing_user is None:
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            client_ip = request.remote_addr
            user = User(email=email, username=username, password=password, regtime=current_time, ip=client_ip)
            db.session.add(user)
            try:
                db.session.commit()
                return jsonify({'success': '注册成功'})
            except sqlalchemy.exc.SQLAlchemyError:
                return jsonify({'error': '注册失败，请稍后重试'})
        else:
            return jsonify({'error': '用户名已存在,请更换或登录'})
    return render_template('/index/register.html')